package wiki.laona.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import wiki.laona.service.ItemsEsService;
import wiki.laona.utils.JsonResult;
import wiki.laona.utils.PagedGridResult;

import javax.annotation.Resource;

/**
 * @author laona
 * @description 商品 controller
 * @date 2022-05-09 16:12
 **/
@Api(value = "商品接口", tags = {"商品信息展示相关接口"})
@RestController
@RequestMapping("items")
public class ItemsController{

    @Resource
    private ItemsEsService itemsEsService;

    @ApiOperation(value = "搜索商品列表", notes = "搜索商品列表", httpMethod = "GET")
    @GetMapping("/es/search")
    public JsonResult search(
            @ApiParam(name = "keywords", value = "搜索关键字", required = true) @RequestParam String keywords,
            @ApiParam(name = "sort", value = "排序规则", required = false) @RequestParam(defaultValue = "k") String sort,
            @ApiParam(name = "page", value = "查询下一页是第几页", required = false)
            @RequestParam(defaultValue = "1") Integer page,
            @ApiParam(name = "pageSize", value = "分页的每一页显示的条数", required = false)
            @RequestParam(defaultValue = "20") Integer pageSize) {

        if (StringUtils.isBlank(keywords)) {
            return JsonResult.errorMsg(null);
        }

        // 没有设置每页条数，则设置默认条数
        if (pageSize == null) {
            pageSize = 20;
        }
        // es 下标是从0开始的，需要自减1
        page--;

        PagedGridResult result = itemsEsService.searchItems(keywords, sort, page, pageSize);

        return JsonResult.ok(result);
    }

}
